<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "gky_we_reply_text".
 *
 * @property string $id
 * @property string $keyword
 * @property integer $keyword_type
 * @property string $content
 * @property string $view_count
 * @property string $sort
 * @property string $weoid
 */
class GkyWeReplyText extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gky_we_reply_text';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['keyword', 'content', 'weoid'], 'required'],
            [['keyword_type', 'view_count', 'sort'], 'integer'],
            [['content'], 'string'],
            [['keyword', 'weoid'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'keyword' => '关键字',
            'keyword_type' => '关键字类型',
            'content' => '回复内容',
            'view_count' => '浏览次数',
            'sort' => '排序号',
            'weoid' => 'Weoid',
        ];
    }

    /**
     * 根据输入关键字查找匹配内容
     *
     * @param $weoid 公众号
     * @param $key   输入关键字
     * @return array|null|string|\yii\db\ActiveRecord
     */
    public static function findByKey($weoid, $key){

        //精确匹配
        $replText = GkyWeReplyText::find()
            ->where(['weoid'=>$weoid,'keyword'=> $key])
            ->orderBy(['sort'=>SORT_ASC])
            ->limit(1)
            ->one();

        if($replText == null){
            $replText = GkyWeReplyText::find()
                ->where(['weoid'=>$weoid,'keyword_type'=>1])
                ->andFilterWhere(['like','keyword',$key])
                ->orderBy(['sort'=>SORT_ASC])
                ->limit(1)
                ->one();
        }

        if($replText == null){
            return '对不起，我们暂时无法处理您的消息';
        }

        return $replText->content;

    }
}
